/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  asdb_response.c
 *  scatterd
 *
 *  Created by Grant Jones on 3/15/08.
 *
 */

#include "edb_main.h"
#include "edb_net_shell.h"
#include "edb_msg_parser.h"
#include "edb_domain.h"
#include "asdb_request.h"
#include "asdb_response.h"

#include <expat.h>

int Depth;

static void XMLCALL start(void *data, const char *el, const char **attr)
{
	int i;

	for (i = 0; i < Depth; i++)
		printf("  ");

	printf("%s", el);

	for (i = 0; attr[i]; i += 2)
	{
		printf(" %s='%s'", attr[i], attr[i + 1]);
	}

	printf("\n");
	Depth++;
}

static void XMLCALL end(void *data, const char *el)
{
	Depth--;
}


/*!
	@function asdb_http_request_done
	@abstract handles ALL response from simpledb, delegates to a callback if specified
	@discussion handles response from simpledb REST API; also removes the initiating
				request from the request queue (so it won't be requested again)
	@param req
	@param arg a simpledb_req_t pointer
*/
void asdb_http_request_done(struct evhttp_request *req, void *arg)
{
	simpledb_req_t *sdbr = arg;
	simpledb_t *sdb = sdbr->sdb;
	printf("asdb_http_request_done\n");
	if( sdbr->cb && req->response_code == HTTP_OK )
		sdbr->cb( sdbr, EVBUFFER_DATA(req->input_buffer), EVBUFFER_LENGTH(req->input_buffer) ); 

	/* remove this request, we don't want to process it again */
	cmap_remove(sdb->requests, sdbr->req_id);

	/* releases the sdbr context as well */
	cmap_destroy(sdbr->req_params);	

	/* start the next request, if any */
	asdb_req_do_next(sdb);
}

typedef struct
{
	int insideItemName;
	edb_value_t *domain_name;
	simpledb_req_t *sdbr;
} query_response_ctx;

static void XMLCALL asdb_query_start(void *data, const char *el, const char **attr)
{
	query_response_ctx *pqrs = data;
	
	if( strcmp( el, "ItemName" ) == 0 )
		pqrs->insideItemName = 1;
}

static void XMLCALL asdb_query_end(void *data, const char *el)
{
	query_response_ctx *pqrs = data;
	
	if( strcmp( el, "ItemName" ) == 0 )
		pqrs->insideItemName = 0;
}
static void XMLCALL asdb_query_characterdata(void *data, const XML_Char *s, int len )
{
	query_response_ctx *pqrs = data;
	if( pqrs->insideItemName )
		asdb_req_queue_get( pqrs->sdbr->sdb,(const char *) pqrs->domain_name->z, pqrs->domain_name->n, s, len );
}

/*!
	@function asdb_get_query_items
	@abstract handles the response to a simpledb query
	@discussion
	@param sdbr
	@param resp
	@param resp_sz	
*/
void asdb_get_query_items( simpledb_req_t *sdbr, const unsigned char *resp, size_t resp_sz )
{
	query_response_ctx qrs;

	XML_Parser p = XML_ParserCreate(NULL);
	if (! p)
	{
		fprintf(stderr, "Couldn't allocate memory for parser\n");
		return;
	}
	qrs.insideItemName = 0;
	qrs.sdbr = sdbr;
	qrs.domain_name = strmap_lookup(sdbr->req_params, "DomainName", 10);
	XML_SetUserData(p, &qrs );
	
	XML_SetCharacterDataHandler(p, asdb_query_characterdata );
	
	XML_SetElementHandler(p, asdb_query_start, asdb_query_end);
    if (XML_Parse(p, (const char *)resp, resp_sz, 1) == XML_STATUS_ERROR)
	{
		fprintf(stderr, "Parse error at line %lu:\n%s\n", (unsigned long)XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p)) );
		
    }

	XML_ParserFree(p);	


}



typedef struct
{
	int insideAttrName;
	int insideAttrValue;
	
	edb_value_t *lastattr_name;
	edb_value_t *lastattr_value;
	
	strmapStruct *itemattrs;
} getattr_response_ctx;

static void XMLCALL asdb_getattr_start(void *data, const char *el, const char **attr)
{
	getattr_response_ctx *ctx = data;
	
	if( strcmp( el, "Name" ) == 0 )
		ctx->insideAttrName = 1;
	else if( strcmp( el, "Value" ) == 0 )
		ctx->insideAttrValue = 1;
}

static void XMLCALL asdb_getattr_end(void *data, const char *el)
{
	getattr_response_ctx *ctx = data;
	if( strcmp( el, "Name" ) == 0 )
		ctx->insideAttrName = 0;
	else if( strcmp( el, "Value" ) == 0 )
		ctx->insideAttrValue = 0;	
	else if( strcmp( el, "Attribute" ) == 0 )
	{
		strmap_assign(ctx->itemattrs, (const char *)ctx->lastattr_name->z, ctx->lastattr_name->n, ctx->lastattr_value );
	}
}
static void XMLCALL asdb_getattr_characterdata(void *data, const XML_Char *s, int len )
{
	getattr_response_ctx *ctx = data;
	if( ctx->insideAttrName )
		ctx->lastattr_name = asdb_req_mkval( ctx->itemattrs->mempool, s, len );
	if( ctx->insideAttrValue )
		ctx->lastattr_value = asdb_req_mkval( ctx->itemattrs->mempool, s, len );

}
/*!
	@function asdb_get_item_attrs
	@abstract handles the response to a simpledb query
	@discussion
	@param sdbr
	@param resp
	@param resp_sz	
*/
void asdb_get_item_attrs( simpledb_req_t *sdbr, const unsigned char *resp, size_t resp_sz )
{
	getattr_response_ctx ctx;

	XML_Parser p = XML_ParserCreate(NULL);
	if (! p)
	{
		fprintf(stderr, "Couldn't allocate memory for parser\n");
		return;
	}
	ctx.insideAttrName = 0;
	ctx.insideAttrValue = 0;
	ctx.itemattrs = cmap_new(NULL);
	
	edb_value_t *domain_name = strmap_lookup(sdbr->req_params, "DomainName", 10);

	strmap_assign( ctx.itemattrs, "_name", 5, strmap_lookup(sdbr->req_params, "ItemName", 8 ) );
	XML_SetUserData(p, &ctx );
	
	XML_SetCharacterDataHandler(p, asdb_getattr_characterdata );
	
	XML_SetElementHandler(p, asdb_getattr_start, asdb_getattr_end);
    if (XML_Parse(p, (const char *)resp, resp_sz, 1) == XML_STATUS_ERROR)
	{
		fprintf(stderr, "Parse error at line %lu:\n%s\n", (unsigned long)XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p)) );
		
    }

	XML_ParserFree(p);	

	printf("******************************\n");
	
	/* this is a bit of a kludge, it could be done a lot easier by simply calling
	** edb_domain_insert_uncond, however that would be cheating, so we instead
	** build this query */
		
	strmapEnumStruct e;
	char *key;
	size_t key_sz;
	edb_value_t *v;
	int item_count = 0;
	int x;
	cmapStruct *query_str = cmap_new(ctx.itemattrs->mempool);
	char *query_cstr;
	size_t query_cstr_len;

	/* construct a query, painfully. */
	cmap_str_concat(query_str, "INSERT INTO " );
	cmap_str_append_bytes(query_str, (const char *)domain_name->z, domain_name->n );
	cmap_str_concat(query_str, " VALUES( ");
	
	strmap_enum( ctx.itemattrs, &e );
	while( (v = strmap_enum_next( &e, &key, &key_sz )) != NULL )
	{
		if( item_count > 0 )
			cmap_str_concat(query_str, ", ");
		cmap_str_append_bytes(query_str, key, key_sz );
		cmap_str_concat(query_str, ":$");
		cmap_str_append_bytes(query_str, key, key_sz );
//		cmap_str_concat(query_str, " ");
		item_count++;
	}

	cmap_str_concat(query_str, ");");
	query_cstr = cmap_str_join(query_str, &query_cstr_len );
	
	edb_net_item_t item;
	edb_net_item_attr_t *attrs = mempool_malloc_named(ctx.itemattrs->mempool, sizeof(edb_net_item_attr_t)*ctx.itemattrs->num, "sync insert attrs");
	item.attr_count = item_count;
	item.attrs = attrs;

	
	strmap_enum( ctx.itemattrs, &e );
	x = 0;
	while( (v = strmap_enum_next( &e, &key, &key_sz )) != NULL )
	{
		/* attribute key must be null-terminated */
		attrs[x].key = mempool_malloc_named( ctx.itemattrs->mempool, key_sz+1, "attribute key string" );
		memcpy( attrs[x].key, key, key_sz );
		attrs[x].key[key_sz] = '\0';
		
		attrs[x].value = (void *)v->z;
		attrs[x].value_sz = v->n;
		
		x++;
	}


	printf("the query is: \"%s\"\n", query_cstr );
	cmapStruct *r;
	
	r = edb_msg_parser( sdbr->sdb->pcs_ptr, ctx.itemattrs->mempool, query_cstr, 1, &item );
	

	
	cmap_destroy(ctx.itemattrs);
}



void asdb_response_dump( simpledb_req_t *sdbr, const unsigned char *resp, size_t resp_sz )
{

	XML_Parser p = XML_ParserCreate(NULL);
	if (! p)
	{
		fprintf(stderr, "Couldn't allocate memory for parser\n");
		return;
	}

	XML_SetElementHandler(p, start, end);
    if (XML_Parse(p, (const char *)resp, resp_sz, 1) == XML_STATUS_ERROR)
	{
		fprintf(stderr, "Parse error at line %lu:\n%s\n", (unsigned long)XML_GetCurrentLineNumber(p), XML_ErrorString(XML_GetErrorCode(p)) );
		
    }

	XML_ParserFree(p);	


}

